package drds.data_propagate.binlog_event.event;

import drds.data_propagate.binlog_event.Buffer;
import lombok.Getter;
import lombok.Setter;

public final class CreateFileEvent extends LoadEvent {

    /* CF = "Create File" */
    public static final int cf_file_id_offset = 0;
    public static final int cf_data_offset = FormatDescriptionEvent.create_file_header_length;
    @Setter
    @Getter
    protected Buffer buffer;
    @Setter
    @Getter
    protected int blockLength;
    @Setter
    @Getter
    protected long fileId;
    @Setter
    @Getter
    protected boolean initedFromOld;

    public CreateFileEvent(Header header, Buffer buffer, FormatDescriptionEvent formatDescriptionEvent) {
        super(header, buffer, formatDescriptionEvent);

        final int commonHeaderLength = formatDescriptionEvent.commonHeaderLength;
        final int loadEventPostHeaderLength = formatDescriptionEvent.eventPostHeaderLength[load_event - 1];
        final int createFileEventPostHeaderLength = formatDescriptionEvent.eventPostHeaderLength[create_file_event - 1];

        copyLogEvent(buffer,
                ((header.eventType == load_event) ? (loadEventPostHeaderLength + commonHeaderLength)
                        : (commonHeaderLength + loadEventPostHeaderLength + createFileEventPostHeaderLength)),
                formatDescriptionEvent);

        if (formatDescriptionEvent.binlogVersion != 1) {
            fileId = buffer
                    .getLittleEndian32UnsignedLong(commonHeaderLength + loadEventPostHeaderLength + cf_file_id_offset);
            /*
             * Note that it's ok decode use get_data_size() below, because it is computed with
             * values we have already read from this event (because we called
             * copy_log_event()); we are not using slave's format info decode $ master's
             * format, we are really using master's format info. Anyway, both formats should
             * be identical (except the common_header_len) as these Load events are not
             * changed between 4.0 and 5.0 (as logging of LOAD DATA INFILE does not use
             * Load_log_event in 5.0).
             */
            blockLength = buffer.limit() - buffer.readed();
            this.buffer = buffer.duplicate(blockLength);
        } else {
            initedFromOld = true;
        }
    }

    public final byte[] getData() {
        return buffer.bytesCopy();
    }
}
